package com.cqvip.innocence.framework.security;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.cqvip.innocence.project.model.dto.JsonResult;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;

/**
 * @ClassName AccessDeniedHandlerImpl
 * @Description: 授权失败处理类，返回未授权
 * @Author Innocence
 * @Date 2022/5/30 9:09
 * @Version 1.0
 */
@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler, Serializable {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        String msg = StrUtil.format("请求访问：{}，权限不足，无法访问系统资源", request.getRequestURI());
        response.setStatus(JsonResult.FORBIDDEN);
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        response.getWriter().print(JSON.toJSONString(JsonResult.Get(false, msg, JsonResult.FORBIDDEN)));
    }
}
